#!/bin/bash
echo "===== 开始磁盘性能测试 ====="
# 记录开始时间
start_time=$(date +%s.%N)
# 磁盘压力测试
fio -filename=testfile -direct=1 -iodepth=32 -rw=randwrite -size=1G -numjobs=4 -group_reporting &> fio_test.log
# 收集指标
cpu_usage=$(top -b -n 1 | grep -v 'Average' | awk '{print $2}' | sort -nr | head -n 1)
memory_usage=$(free -m | awk '/Mem:/ {print $3}')
disk_io=$(iostat -d -k | awk '/sda/ {print $3}')
# 检查是否有进程导致高负载
TOP_PID=$(ps -eo pid,pcpu --sort=-pcpu | grep -v "PID" | head -n 1 | awk '{print $1}')
TOP_CPU_USAGE=$(ps -p $TOP_PID -o %cpu= | awk '{print int($1)}')
if [ "$TOP_CPU_USAGE" -ge "90" ]; then
    echo "检测到高CPU使用率，终止进程: $TOP_PID"
    kill -9 $TOP_PID
fi
# 网络连接数检查和优化
echo "优化网络连接数配置"
sudo sysctl -p
sudo iptables -I INPUT -m state --state NEW -m recent --set --name CONN_LIMIT --rps 10
sudo nmap -sS -oG conn_scan_output.txt
# 记录结束时间
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time" | bc)
echo "===== 测试摘要 ====="
echo "总执行时间: ${duration}秒"
echo "最高CPU使用率: ${cpu_usage}%"
echo "内存使用量: ${memory_usage}MB"
echo "磁盘IO: ${disk_io}KB/s"
# 调整后性能验证
post_cpu=$(top -b -n 1 | grep -v 'Average' | awk '{print $2}' | sort -nr | head -n 1)
post_memory=$(free -m | awk '/Mem:/ {print $3}')
post_disk_io=$(iostat -d -k | awk '/sda/ {print $3}')
echo "===== 调整前后对比 ====="
echo "调整前CPU使用率: ${cpu_usage}%"
echo "调整后CPU使用率: ${post_cpu}%"
echo "调整前内存使用量: ${memory_usage}MB"
echo "调整后内存使用量: ${post_memory}"
echo "调整前磁盘IO: ${disk_io}KB/s"
echo "调整后磁盘IO: ${post_disk_io}"
# 结构化输出
echo "===== 性能指标 ====="
echo '{
    "total_time": "'$duration'",
    "cpu_usage": "'$cpu_usage'",
    "memory_usage": "'$memory_usage'",
    "disk_io": "'$disk_io'"
}'